#!/usr/bin/env python3
"""
HTTPS协议处理器
"""
import asyncio
import base64
import random
import ssl
import uuid
from datetime import datetime, timezone
from typing import Optional

from .http_handler import HTTPHandler
from .logger import op_logger

class HTTPSHandler(HTTPHandler):
    """
    HTTPS协议处理器，通过SSL包装HTTP处理器实现HTTPS服务
    """

    def __init__(self, host, port, log_file, certfile: str, keyfile: str):
        """
        初始化HTTPS处理器

        Args:
            host (str): 监听主机地址
            port (int): 监听端口
            log_file (str): 日志文件路径
            certfile (str): SSL证书文件路径
            keyfile (str): SSL密钥文件路径
        """
        super().__init__(host, port, log_file)
        self.name = "https"
        self.certfile = certfile
        self.keyfile = keyfile
        # 生成带hash的动态路径
        self.dynamic_paths = self._generate_dynamic_paths()

    async def start(self):
        """
        启动HTTPS服务器
        """
        try:
            # 创建SSL上下文
            ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
            ctx.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1  # 禁用旧版本
            ctx.load_cert_chain(certfile=self.certfile, keyfile=self.keyfile)
            # 添加更强的SSL配置
            ctx.set_ciphers('ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20:!aNULL:!MD5:!DSS')
            self._server = await asyncio.start_server(self._handle, host=self.host, port=self.port, ssl=ctx)
            addrs = ", ".join(str(sock.getsockname()) for sock in self._server.sockets)
            op_logger.info("HTTPS监听于 %s", addrs)
            asyncio.create_task(self._server.serve_forever())
        except FileNotFoundError:
            op_logger.error("找不到SSL证书文件: certfile=%s keyfile=%s", self.certfile, self.keyfile)
            op_logger.error("请使用--generate-cert参数自动生成证书，或手动提供证书文件")
        except Exception as e:
            op_logger.exception("HTTPS服务器启动失败: %s", e)
